import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Game extends JPanel implements MouseListener{
	Game(){
		deck = new Stack<Card>();
		try{
			Scanner s = new Scanner(new File("cards.ini"));
			while(s.hasNext()){
				String temp = s.next();
				CardImage image = Card.stringToCardImage(temp);
				String id = s.next();
				deck.add(new Card(id, image));
			}
		} catch (FileNotFoundException e){
			System.out.println(e);
		} catch (CardTypeNotFoundException e){
			System.out.println(e);
		}
		Random r = new Random(System.currentTimeMillis());
		for(int i = 0; i < r.nextInt(30); i++){
			shuffleDeck();
		}
		this.setLayout(new BorderLayout());
		lastCards = new Vector<Card>();
		board = new CardGrid(deck);
		board.addMouseListener(this);
		
		score = new Score();
		message = new JLabel(" ");
		add(board, BorderLayout.CENTER);
		add(score, BorderLayout.NORTH);
		add(message, BorderLayout.SOUTH);


		//System.out.println(this);


	}
	Game(String save){
		String[] parts = save.split("\n");
		for(int i = 0; i < parts.length; i++){
			if(parts[i].contains("<Game")){
				String s[] = parts[i].split(" ");
				for(int x = 0; x < s.length; x++){
					if(s[x].contains("score")){
						String t[] = s[x].split("\"");
						score = new Score(Integer.valueOf(t[1]));
					}else if(s[x].contains("message")){
						String t[] = s[x].split("\"");
						message = new JLabel(t[1]);
					}
				}
			}
			if(parts[i].contains("<CardGrid>")){
				String s = "<CardGrid>";
				i++;
				while(!parts[i].contains("</CardGrid>")){
					s += "\n"+parts[i];
					i++;
				}
				s += "\n</CardGrid>";
				board = new CardGrid(s);
			}
		}
		this.setLayout(new BorderLayout());
		lastCards = new Vector<Card>();
		
		board.addMouseListener(this);
		add(board, BorderLayout.CENTER);
		add(score, BorderLayout.NORTH);
		add(message, BorderLayout.SOUTH);

	}
	
	
	private void shuffleDeck(){
		int numOfCards = deck.size();
		Stack<Card> halfDeck = new Stack<Card>();
		while(deck.size() > numOfCards / 2){
			halfDeck.add(deck.pop());
		}
		Stack<Card> newDeck = new Stack<Card>();
		while(newDeck.size() < numOfCards){
			newDeck.add(halfDeck.pop());
			newDeck.add(deck.pop());
		}
		deck = newDeck;
	}
	
	public String displayDeck(){
		String s = "";
		Stack<Card> tempDeck = new Stack<Card>();
		while(!deck.isEmpty()){
			Card c = deck.pop();
			s += c.toString();
			s += "\n";
			
			tempDeck.add(c);
		}
		while(!tempDeck.isEmpty()){
			deck.add(tempDeck.pop());
		}
		
		return s;
	}
	public void mouseClicked(MouseEvent e) {

		if(e.getSource() instanceof Card){
			Card c = (Card)e.getSource();
			if(c.isFlipped()){
				return;
			}
			if(lastCards.size() > 1){
				int count = 0;
				while(!lastCards.isEmpty()){ 
					count++;
					Card t = lastCards.remove(lastCards.size() - 1); 
					t.flip();
				}
				message.setText("Sorry your two cards did not match");
				score.misMatch();
				return;
				
			} else if(!lastCards.isEmpty()){
				if(c.equals(lastCards.lastElement())){
					lastCards.lastElement().removeMouseListener(this);
					c.removeMouseListener(this);
					c.flip();
					lastCards.removeAll(lastCards);
					message.setText("Nice! Your two cards Match");
					score.match();
					matched++;
					if(matched == (board.numOfCards() / 2) ){
						message.setText("Congratulations! You won");
					}
					return;
				}
			}
			lastCards.add(c);
			c.flip();
			message.setText("You found a " + c.getFace());


		}
			System.out.println("Size: " + lastCards.size() + "," + lastCards.toString());		
			
	}
	class CKey extends java.awt.event.KeyAdapter {
		public void keyPressed(java.awt.event.KeyEvent event) {
		    if (event.getKeyCode() == java.awt.event.KeyEvent.VK_S)
		    	  if (event.isControlDown()) System.out.println("run");
		}
	}
	
	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e)  {}
	public void mousePressed(MouseEvent e) {}
	public void mouseReleased(MouseEvent e){}

	public String toString(){
		String s = "";
		while(!lastCards.isEmpty()){
			
		}
		s += "<Game " + score + ">\n";
		s += "\t"+ board;
		s += "\n</Game>";
		return s;
	}
	
	private Score score;
	private JLabel message;
	private Vector<Card> lastCards;
	private CardGrid board;
	private Stack<Card> deck;
	
	private int matched = 0;
	
	public static void main(String[] args){
		String s = "<Game score=\"0\" message=\"Test\">\n<CardGrid>\n<Card id=\"9\" cardImage=\"preist\" flipped=\"false\"  />\n<Card id=\"5\" cardImage=\"knight\" flipped=\"false\"  />\n<Card id=\"1\" cardImage=\"king\" flipped=\"false\"  />\n<Card id=\"4\" cardImage=\"queen\" flipped=\"false\"  />\n<Card id=\"8\" cardImage=\"bishop\" flipped=\"false\"  />\n<Card id=\"12\" cardImage=\"peasant\" flipped=\"false\"  />\n<Card id=\"10\" cardImage=\"preist\" flipped=\"false\"  />\n<Card id=\"6\" cardImage=\"knight\" flipped=\"false\"  />\n<Card id=\"2\" cardImage=\"king\" flipped=\"false\"  />\n<Card id=\"3\" cardImage=\"queen\" flipped=\"false\"  />\n<Card id=\"7\" cardImage=\"bishop\" flipped=\"false\"  />\n<Card id=\"11\" cardImage=\"peasant\" flipped=\"false\"  />\n</CardGrid>\n</Game>";
		Game g = new Game(s);
		JFrame f = new JFrame();
		f.add(g);
		f.setVisible(true);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.pack();
		
		
	}

	
}
